import pymysql
import logging
from configs.configs import *
logger = logging.getLogger(__name__)



class MYSQLDB:

    def __init__(self):
        self.conn = pymysql.connect(
            host=mysql_info["host"],
            port=mysql_info["port"],
            user=mysql_info["user"],
            password=mysql_info["password"],
            db=mysql_info["db"],
            charset="utf8"
        )
        self.cur = self.conn.cursor(cursor=pymysql.cursors.DictCursor)

    def __del__(self):
        try:
            # 关闭游标
            self.cur.close()
            # 关闭连接
            self.conn.close()
        except Exception as ex:
            logger.error(f"出错了：{ex}")

    #查询
    def query(self,initsql):
        try:
            self.cur.execute(initsql)
            data = self.cur.fetchall()
            return data
        except Exception as ex:
            logger.error(f"出错了：{ex}")
            raise
    #修改
    def execute(self,initsql):
        try:
            rows = self.cur.execute(initsql)
            self.conn.commit()
            return rows
        except Exception as ex:
            logger.error(f"出错了:{ex}")
            self.conn.rollback()
            raise




#查询sql语句
def execute_init_sql(initsql):
    mysqldb = MYSQLDB()
    if initsql.strip().startswith("select"):
        res = mysqldb.query(initsql)
        logger.info("{}查询结果是：{}".format(initsql, res))
    else:
        res = mysqldb.execute(initsql)
        logger.info("操作成功")